<?php

namespace App\Http\Controllers\Web\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Web\StoreRequest;
use App\Models\Examination;
use App\Models\Setting;
use Carbon\Carbon;
use Dingo\Api\Http\Response;
use Illuminate\Http\Request;

class ExamController extends Controller
{
    /**
     * 我的考试
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        // 科目查询
        $subjectId = $request->input('subject_id');

        // 获取科目分类
        $subject = cacheSubject();

        // 获取已经考完试的试卷数据
        $data = Examination::query()
            ->select('id', 'name', 'subject_id', 'start_time', 'over_time', 'passing_mark', 'test_list_id', 'status')
            ->when($request->input('subject_id'), function ($query) use ($subjectId) {
                $query->where('subject_id', $subjectId);
            })
            ->where([
                ['type', 1],
                ['examination_mode', 0],
            ])
            ->orWhere([
                ['type', 1],
                ['examination_mode', 1],
                ['peoples', 'like', '%,' . auth()->id() . ',%'],
            ])
            ->orderBy('created_at', 'desc')
            ->with('subject:id,name')
            ->with('testList:id,name')
            ->with('result:examination_id,fraction')
            ->get();

        return $this->response->array(['subject' => $subject, 'data' => $data]);
    }

    /**
     * 进入考场
     *
     * @return Response|void
     */
    public function get(StoreRequest $request)
    {
        // 获取 状态为 1 类型 1 的考场
        $exam = getExam(1, $request->input('examination_id') ?? null);

        if (!$exam) {
            return $this->response->errorBadRequest('没有相关的考试哦');
        }

        // 截止进场时间
        if (Carbon::now()->gt(Carbon::parse($exam->over_time))) {
            return $this->response->errorBadRequest('考试已经截止进场');
        }

        // 考试须知
        $setting = Setting::query()->where('type', 'toefl_ibt')->get();

        return $this->response->array(['exam' => $exam, 'setting' => $setting]);
    }

    /**
     * 开始考试
     * @param StoreRequest $request
     * @return Response
     */
    public function store(StoreRequest $request)
    {
        $data = createStudentResult($request);

        return $this->response->array(['data' => $data]);
    }
}
